package com.jijuxie.common.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.io.File;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 文件上传配置
 * 
 * @author jijuxie
 */
@Configuration
public class FileUploadConfig implements WebMvcConfigurer {
    
    private static final Logger log = LoggerFactory.getLogger(FileUploadConfig.class);
    
    @Value("${upload.path:D:/jijuxie/upload/}")
    private String uploadPath;
    
    @Value("${upload.url:/profile/}")
    private String uploadUrl;
    
    @Value("${upload.subdirs.avatars:avatars/}")
    private String avatarsDir;
    
    @Value("${upload.subdirs.chat:chat/}")
    private String chatDir;
    
    @Value("${upload.subdirs.house:house/}")
    private String houseDir;
    
    @Value("${upload.subdirs.sys:system/}")
    private String sysDir;
    
    /**
     * 添加资源处理器，将物理路径映射到访问路径
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 确保上传根目录存在
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            boolean created = uploadDir.mkdirs();
            log.info("创建上传根目录: {}, 结果: {}", uploadPath, created ? "成功" : "失败");
        }
        
        // 创建头像子目录
        createSubDir(avatarsDir, "头像");
        
        // 创建聊天图片子目录
        createSubDir(chatDir, "聊天图片");
        
        // 创建房源图片子目录
        createSubDir(houseDir, "房源图片");
        
        // 创建系统图片子目录
        createSubDir(sysDir, "系统图片");
        
        // 主要资源映射
        registry.addResourceHandler(uploadUrl + "**")
                .addResourceLocations("file:" + uploadPath);
        
        // 添加专门的头像映射 - 确保/profile/avatars/**能访问到avatars目录
        registry.addResourceHandler(uploadUrl + "avatars/**")
                .addResourceLocations("file:" + uploadPath + avatarsDir);
                
        log.info("已配置静态资源映射: {} -> {}", uploadUrl, uploadPath);
        log.info("已配置头像资源映射: {}avatars/** -> {}{}", uploadUrl, uploadPath, avatarsDir);
    }
    
    /**
     * 创建子目录
     * 
     * @param subDir 子目录名称
     * @param dirType 目录类型描述
     */
    private void createSubDir(String subDir, String dirType) {
        File dir = new File(uploadPath + subDir);
        if (!dir.exists()) {
            boolean created = dir.mkdirs();
            log.info("创建{}目录: {}, 结果: {}", dirType, dir.getAbsolutePath(), created ? "成功" : "失败");
        }
    }
} 